<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Session;
class goodcontroller extends Controller
{
    //index
    public function index(Request $request,$tid='0')
    {
        $keywords = $request -> input('keywords');
        $num = $request -> input('num',9);
        if(empty($keywords)) 
        {

            $data = DB::table('goods')
                ->leftJoin('types','goods.tid','=','types.tid')
                ->where('path','like','%'.$tid.'%')
                ->paginate($num); 
        }else
        {
            $data = DB::table('goods')
                ->leftJoin('types','goods.tid','=','types.tid')
                ->where('gname','like','%'.$keywords.'%')
                ->paginate($num); 
        }
        $case = DB::table('goods')
                ->where('scnt','>=','300')
                ->limit(2)
                ->get();
        
		return view('home.good.index',['data' => $data, 'request' => $request -> all(), 'title' => '商品信息','case'=>$case]);
		// return view('home.good.index');
    }

    public function list($gid)
    {
        if (!empty(session('homeM'))) 
        {
            $status = DB::table('order')
            ->leftJoin('detail','order.oid','=','detail.oid')
            ->where('uid',session('homeM')->uid)
            ->get();
        }else
        {
            $status = [];
        }
        
    	$data = DB::table('goods')
         ->leftJoin('prop', 'goods.gid', '=', 'prop.gid')
         ->where('goods.gid', $gid)
         ->first();
        $comment = DB::table('comment')
         ->leftJoin('goods','goods.gid','=','comment.gid')
         ->leftJoin('users','users.uid','=','comment.uid')
         ->where('goods.gid',$gid)
         ->get();
        $cnt = DB::table('comment') 
        ->select(DB::raw('count(uid) as cnt'))
        ->where('gid',$gid)
        ->first();

        if(!empty($cnt -> cnt))
        {
            $sum = 0;
            foreach($comment as $k => $v)
            {
                $sum += $v->pf;
            }
            
            $avg = $sum / $cnt -> cnt;
        }else
        {
            $avg = 0;
        }

        $data->gid = $gid;

        $sim = DB::table('goods')->where('tid',$data->tid)->limit(3)->get();
        $case = DB::table('goods')
                ->where('scnt','>=','300')
                ->limit(2)
                ->get();
    	return view('home.good.list',['data' => $data, 'title' => '商品详情','sim'=>$sim,'comment'=>$comment,'status'=>$status,'avg'=>$avg,'case'=>$case]);
    }

    public function insert(Request $request)
    {
        
        $data = $request -> except('_token');
        $data['uid'] = session('homeM')->uid;
        $gid = $data['gid'];
        $res = DB::table('comment') -> insert($data);
        if($res)
        {
            return back() -> with(['info' => '添加成功']);
        }else
        {
            return back() -> with(['info' => '添加失败']);
        }
    }

}
